package com.cloudbroker.bcs.platform.ltb.middle.bizservice.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.validatioin.constants.ValidationErrorCodes;
import com.cloudbroker.bcs.csvc.lightinvesting.api.entity.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedSecT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.t2service.LedT2Service;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.fansRelated.*;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.request.interestRelated.CombineApplyForm;
import com.cloudbroker.bcs.csvc.lightinvesting.api.vo.response.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.admin.back.UserEntityVO;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.TagsAddForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.push.vo.TagsRemoveForm;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.CombineBizService;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.back.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.transaction.vo.*;
import com.cloudbroker.bcs.platform.ltb.bizapi.service.user.back.UsersQueryVo;
import com.cloudbroker.bcs.platform.ltb.middle.entity.CombinationEntity;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.lightinvesting.LightinvestingService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.push.PushExtService;
import com.cloudbroker.bcs.platform.ltb.middle.extservice.usercenter.UserCenterService;
import com.cloudbroker.bcs.platform.ltb.middle.service.CombineService;
import com.cloudbroker.bcs.platform.ltb.middle.service.PushService;
import com.cloudbroker.bcs.platform.ltb.middle.service.UserService;
import com.cloudbroker.bcs.platform.ltb.middle.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

import static com.cloudbroker.bcs.platform.ltb.bizapi.constants.HSBCPSErrorCodes.ClientErr.COMBINE_NAME_IS_REPEAT;


/**
 * Created by tianrui on 2016/7/26.
 */

@Service
public class CombineBizServiceImpl implements CombineBizService {

    //调用后台接口
    @Resource
    private LightinvestingService lightinvestingService;

    //组合费用运算
    private final int UNIT_COST = 100;

    @Resource
    private CombineService combineService;
    @Resource
    private LedT2Service ledT2Service;
    @Resource
    private UserService userService;
    @Resource
    private UserCenterService userCenterService;
    @Resource
    private PushExtService pushExtService;
    @Resource
    private LedSecT2Service ledSecT2Service;
//    @Resource
//    private IndiviDemandT2 indiviDemandT2;

    @Resource
    private PushService pushService;
    /**
     * 1.组合名称、关注数、组合code落地
     * 2.调用后台组合申请接口
     * */
    @Override
    @Transactional
    public CombineApplyBack CombineApply(CombineCreateForm form) {
        //插入组合时同一券商不允许组合名称相同
        int combineCount = combineService.combineNameIsExist(form.getCombi_name());
        if (combineCount != 0){
            return VOUtil.genErrorResult(COMBINE_NAME_IS_REPEAT, CombineApplyBack.class);
        }
        CombineApplyForm combineApplyForm = new CombineApplyForm();
        combineApplyClassSwap(combineApplyForm, form);
        combineApplyForm.setNeed_user_id(form.getNeed_user_id());
        CombineApplyVo combineApplyVo = lightinvestingService.func_combine_apply(combineApplyForm);
        if (!combineApplyVo.getError_no().equals("0")){
            return VOUtil.genBGErrorResult(combineApplyVo.getError_no(), combineApplyVo.getError_info(),CombineApplyBack.class);
        }
        if(null==combineApplyVo){
            return VOUtil.setSuccessResult(new CombineApplyBack());
        }
        CombinationEntity combinationEntity = new CombinationEntity();
        combinationEntity.setCompany_id(form.getCompany_id());
        combinationEntity.setCombination_name(form.getCombi_name());
        combinationEntity.setCombination_code(combineApplyVo.getCombi_code());
        combinationEntity.setUser_id(form.getUser().getUser_id());
        combinationEntity.setCreate_time(System.currentTimeMillis());
//        if("20020".equals(form.getUser().getSendercomp_id())){//如果是西南
//            combinationEntity.setClose_status(0);//待审核状态
//        }
        //中台组合落地
        combineService.addCombineInfo(combinationEntity);
        CombineApplyBack combineApplyBack = new CombineApplyBack();
        combineApplyBack.setCombi_code(combineApplyVo.getCombi_code());
        combineApplyBack.setApply_no(combineApplyVo.getApply_no());
        combineApplyBack.setBusin_account(combineApplyVo.getBusin_account());
        combineApplyBack.setClient_branch_no(combineApplyVo.getClient_branch_no());
        combineApplyBack.setCompany_id(combineApplyVo.getCompany_id());
        combineApplyBack.setClient_id(combineApplyVo.getClient_id());
        combineApplyBack.setBusinsys_no(combineApplyVo.getBusinsys_no());
//        if(null==combinationEntity.getClose_status() || ""==combinationEntity.getClose_status().toString()){
//            combineApplyBack.setComb_status(1);
//        }
//        combineApplyBack.setComb_status(combinationEntity.getClose_status());
        return VOUtil.setSuccessResult(combineApplyBack);
    }

    /**
     * 组合关注
     * */
    @Override
    public HSBCPSBackVO CombineFocus(CombineFocusForm form) {
        combineService.combineFocus(new CombinationEntity(form.getUser().getUser_id(), form.getCombi_code(),
                form.getCompany_id()));
        CombineCollectForm combFocusForm = new CombineCollectForm();
        combFocusForm.setSendercomp_id(form.getSendercomp_id());
        combFocusForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        combFocusForm.setCombi_code(form.getCombi_code());
        combFocusForm.setUser_token(form.getUser_token());
        combFocusForm.setNeed_user_id(form.getNeed_user_id());
        CombineCollectVo combFocusVo = lightinvestingService.func_comb_focus(combFocusForm);
        if (!combFocusVo.getError_no().equals("0")){
            return VOUtil.genBGErrorResult(combFocusVo.getError_no(),combFocusVo.getError_info(), HSBCPSBackVO.class);
        }
        if(null==combFocusVo){
            return VOUtil.setSuccessResult(new HSBCPSBackVO());
        }
        if(VOUtil.isSuccess(combFocusVo)){
            TagsAddForm tagsAddForm = new TagsAddForm();
            tagsAddForm.setTag(form.getCombi_code());
            tagsAddForm.setUser_id(form.getUser().getUser_id());
            tagsAddForm.setCompany_id(form.getCompany_id());
            tagsAddForm.setSendercomp_id(form.getCompany_id());
            pushService.tagsAdd(tagsAddForm);
        }
//        //设置标签
//        TagsAddForm tagsForm = new TagsAddForm();
//        tagsForm.setUser(form.getUser());
//        tagsForm.setTag(form.getCombi_code());
//        tagsForm.setCompany_id(form.getCompany_id());
//        tagsForm.setSendercomp_id(form.getSendercomp_id());
//        pushService.tagsAdd(tagsForm);
        return VOUtil.genSuccessBackVo();
    }

    /**
     * 组合关注取消
     * */
    @Override
    public HSBCPSBackVO CombineFocusCancel(CombineFocusForm form) {
        combineService.combineFocusCancel(new CombinationEntity(form.getUser().getUser_id(), form.getCombi_code(),
                form.getCompany_id()));
        CombCollectCancelForm combFocusFormCancel = new CombCollectCancelForm();
        combFocusFormCancel.setSendercomp_id(form.getSendercomp_id());
        combFocusFormCancel.setUser_id(String.valueOf(form.getUser().getUser_id()));
        combFocusFormCancel.setCombi_code(form.getCombi_code());
        combFocusFormCancel.setUser_token(form.getUser_token());
        combFocusFormCancel.setNeed_user_id(form.getNeed_user_id());
        CombCollectCancelVo combFocusCancelVo = lightinvestingService.func_comb_focus_cancel(combFocusFormCancel);
        if (!combFocusCancelVo.getError_no().equals("0")){
            return VOUtil.genBGErrorResult(combFocusCancelVo.getError_no(),
                    combFocusCancelVo.getError_info(), HSBCPSBackVO.class);
        }
        if(null==combFocusCancelVo){
            return VOUtil.setSuccessResult(new HSBCPSBackVO());
        }
        //删除标签
        if(VOUtil.isSuccess(combFocusCancelVo)){
            TagsRemoveForm tagsRemoveForm = new TagsRemoveForm();
            tagsRemoveForm.setTag(form.getCombi_code());
            tagsRemoveForm.setUser_id(form.getUser().getUser_id());
            tagsRemoveForm.setCompany_id(form.getCompany_id());
            tagsRemoveForm.setSendercomp_id(form.getCompany_id());
            pushService.tagsDelete(tagsRemoveForm);
        }
        return VOUtil.genSuccessBackVo();
    }

    /**
     * 组合概要信息查询
     * */
    @Override
    public CombineSummaryList CombineSummaryQuery(CombineSummaryQryForm form) {
        List<CombineCode> combi_code_list = null;
        try {
            combi_code_list = JSONObject.parseArray(form.getData_list(), CombineCode.class);
        }catch (Exception e){
            return VOUtil.genErrorResult(ValidationErrorCodes.PARAM_MALFORMED,CombineSummaryList.class);
        }
        //去重
        List<CombineCode> new_list = new ArrayList<CombineCode>();
        HashSet set = new HashSet();
        for (Iterator iterator = combi_code_list.iterator(); iterator.hasNext();){
            CombineCode element = (CombineCode) iterator.next();
            if (set.add(element.getCombin_code())){
                new_list.add(element);
            }
        }
        combi_code_list.clear();
        combi_code_list.addAll(new_list);
        List<CombineSummaryData> summaryList = new ArrayList<CombineSummaryData>();
        //轮训后台组合基本信息查询接口
        for (CombineCode code : combi_code_list){
            CombDetailForm combDetailForm = new CombDetailForm();
            CombineSummaryData combineSummaryData = new CombineSummaryData();
            combDetailForm.setSendercomp_id(form.getSendercomp_id());
            combDetailForm.setOp_branch_no(form.getOp_branch_no());
            combDetailForm.setOp_station(form.getOp_station());
            combDetailForm.setOp_entrust_way(form.getOp_entrust_way());
            combDetailForm.setBranch_no(form.getBranch_no());
            combDetailForm.setCombi_code(code.getCombin_code());
            combDetailForm.setSendercomp_id(form.getSendercomp_id());
            combDetailForm.setUser_token(form.getUser_token());
            combDetailForm.setNeed_user_id(form.getNeed_user_id());
            CombDetailQryBackVo combDetailQryBackVo = lightinvestingService.func_comb_details(combDetailForm);
            if (combDetailQryBackVo.getData_list() == null){
                continue;
            }
            List<CombDetailResult> combDetailResults = combDetailQryBackVo.getData_list();
            CombDetailResult combDetailResult = combDetailResults.get(0);
            //返回前端
            combineSummaryData.setCombi_code(combDetailResult.getCombi_code());
            combineSummaryData.setCollect_num(String.valueOf(combDetailResult.getCollect_num()));
            combineSummaryData.setCombi_name(combDetailResult.getCombi_name());
            combineSummaryData.setIncome_ratio(String.valueOf(combDetailResult.getIncome_ratio()));
            combineSummaryData.setToday_income_ratio(String.valueOf(combDetailResult.getToday_income_ratio()));
            summaryList.add(combineSummaryData);
        }
        CombineSummaryList combineSummaryList = new CombineSummaryList();
        combineSummaryList.setData_list(summaryList);
        return VOUtil.setSuccessResult(combineSummaryList);
    }


    /**
     * 组合申请(创建),将中台的组合创建信息打入后台组合申请信息请求
     * @param retForm
     * @param form
     */
    private void combineApplyClassSwap(CombineApplyForm retForm, CombineCreateForm form){
        retForm.setUser_token(form.getUser_token());
        retForm.setComb_fare(form.getComb_fare());
        retForm.setExpect_income_ratio(form.getExpect_income_ratio());
        retForm.setEnd_date(form.getEnd_date());
        retForm.setBegin_date(form.getBegin_date());
        retForm.setCombine_kind(form.getCombine_kind());
        retForm.setPromotion_flag(form.getPromotion_flag());
        retForm.setRemark(form.getRemark());
        retForm.setTest_answer(form.getTest_answer());
        retForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        retForm.setSummary(form.getSummary());
        retForm.setCombi_name(form.getCombi_name());
        retForm.setTopic_name_str(form.getTopic_name_str());
        retForm.setInvest_style(form.getInvest_style());
//        //此处为每月费用 中台数据存到分的整数
//        StringBuffer per_month_str = new StringBuffer(form.getFare_per_month_str());
//        int dotPos = per_month_str.indexOf("|");
//        int price = 0;
//        if (dotPos != -1){
//            int dotNum = Integer.valueOf(per_month_str.substring(dotPos + 1));
//            int realNum = Integer.valueOf(per_month_str.substring(0, dotPos));
//            price = realNum * UNIT_COST + dotNum;
//        }else {
//            price = Integer.valueOf(form.getFare_per_month_str()) * UNIT_COST;
//        }
//        retForm.setFare_per_month_str(String.valueOf(price));
        retForm.setFare_per_month_str(form.getFare_per_month_str());
        retForm.setFare_per_quarter_str(form.getFare_per_quarter_str());
        retForm.setFare_per_halfyear_str(form.getFare_per_halfyear_str());
        retForm.setFare_per_year_str(form.getFare_per_year_str());
        retForm.setBackground_info(form.getBackground_info());
        retForm.setSendercomp_id(form.getSendercomp_id());
        retForm.setFocus_postpone_days(form.getFocus_postpone_days());
        retForm.setComtag_str(form.getComtag_str());
        retForm.setCombi_feature(form.getCombi_feature());// combi_feature
    }

    /**
     * 组合搜索：出参增加头像
     * @param form
     * @return
     */
    public CombineSearchList CombineSearch(CombineMidSearchForm form){
        CombineSearchForm combineSearchForm = new CombineSearchForm();
        combineSearchForm.setSendercomp_id(form.getSendercomp_id());
        combineSearchForm.setOp_branch_no(form.getOp_branch_no());
        combineSearchForm.setOp_station(form.getOp_station());
        combineSearchForm.setOp_entrust_way(form.getOp_entrust_way());
        combineSearchForm.setBranch_no(form.getBranch_no());
        combineSearchForm.setTopic_name_str(form.getTopic_name_str());
        combineSearchForm.setCombi_name(form.getCombi_name());
        combineSearchForm.setAlias_name(form.getAlias_name());
        combineSearchForm.setPosition_str(form.getPosition_str());
        combineSearchForm.setRequest_num(form.getRequest_num());
        combineSearchForm.setInvest_style(form.getInvest_style());
        combineSearchForm.setCombine_kind(form.getCombine_kind());
        combineSearchForm.setQuery_flag(form.getQuery_flag());
        combineSearchForm.setUser_token(form.getUser_token());
        CombineSearchFormQryBackVo combineSearchFormQryBackVo = lightinvestingService.func_combine_search(combineSearchForm);

        CombineSearchList combineSearchList = new CombineSearchList();

        List<CombineSearchData> combineSearchDatas = new ArrayList<>();
        List<CombineSearchFormResult> bgCombineSearchResult = combineSearchFormQryBackVo.getData_list();
        if(!combineSearchFormQryBackVo.getError_no().equals("0")){
            return VOUtil.genErrorResult(combineSearchFormQryBackVo.getError_no(),combineSearchFormQryBackVo.getError_info(),CombineSearchList.class);
        }
        if (combineSearchFormQryBackVo.getData_list() == null || bgCombineSearchResult ==null ||
                bgCombineSearchResult.size() == 0) {
            return VOUtil.setSuccessResult(combineSearchList);
        }
        List<Long> userIds= new ArrayList<>();
        for (CombineSearchFormResult temp : bgCombineSearchResult) {
            userIds.add(Long.valueOf(temp.getUser_id()));
        }
        Map<Long,UserEntityVO> avatarMap = leaderAvatarMap(userIds);
        for (CombineSearchFormResult temp : bgCombineSearchResult){
            CombineSearchData data = new CombineSearchData();
            data.setCombi_code(temp.getCombi_code());
            data.setCombi_name(temp.getCombi_name());
            data.setCombine_kind(temp.getCombine_kind());
            data.setSummary(temp.getSummary());
            data.setTopic_name_str(temp.getTopic_name_str());
            data.setCreate_date(temp.getCreate_date());
            data.setCombi_status(temp.getCombi_status());
            data.setUser_id(temp.getUser_id());
            data.setAlias_name(temp.getAlias_name());
            data.setIncome_ratio(temp.getIncome_ratio());
            data.setFocus_num(temp.getFocus_num());
            data.setFollow_num(temp.getFollow_num());
            data.setModify_date(temp.getModify_date());
            data.setWorth_value(temp.getWorth_value());
            data.setHold_ratio(temp.getHold_ratio());
            data.setFile_path(temp.getFile_path());
            data.setBackground_info(temp.getBackground_info());
            data.setAssess_level(temp.getAssess_level());
            data.setPosition_str(temp.getPosition_str());
            data.setWeek_income_ratio(temp.getWeek_income_ratio());
            data.setMonth_income_ratio(temp.getMonth_income_ratio());
            data.setYear_income_ratio(temp.getYear_income_ratio());
            data.setAnnual_income_ratio(temp.getYear_income_ratio());
            data.setCombine_kind(temp.getCombine_kind());
            data.setInvest_style(temp.getInvest_style());
            data.setCollect_num(temp.getCollect_num());
            data.setCollect_cancel_num(temp.getCollect_cancel_num());
            data.setIncome_ratio_stability(temp.getIncome_ratio_stability());
            data.setComprehensive_score(temp.getComprehensive_score());
            data.setIs_reach(temp.getIs_reach());
            data.setComtag_str(temp.getComtag_str());
            data.setBegin_date(temp.getBegin_date());
            data.setEnd_date(temp.getEnd_date());
            data.setCombi_feature(temp.getCombi_feature());
            UserEntityVO userEntityVO = avatarMap.get(Long.valueOf(temp.getUser_id()));
            if(userEntityVO != null){
                data.setLeader_avatar(userEntityVO.getAvatar());
                data.setAlias_name(userEntityVO.getAlias_name());
            }
            combineSearchDatas.add(data);
        }
        combineSearchList.setData_list(combineSearchDatas);
        return VOUtil.setSuccessResult(combineSearchList);

    }

    @Override
    public CombRankQryBackVo comb_rank(CombineRankForm form) {//组合排名
        CombRankForm combRankForm = new CombRankForm();
        combRankForm.setOp_branch_no(form.getOp_branch_no());
        combRankForm.setOp_entrust_way(form.getOp_entrust_way());
        combRankForm.setOp_station(form.getOp_station());
        combRankForm.setBranch_no(form.getBranch_no());
        combRankForm.setPassword(form.getPassword());
        combRankForm.setPassword_type(form.getPassword_type());
        combRankForm.setUser_token(form.getUser_token());
        combRankForm.setSendercomp_id(form.getSendercomp_id());
        combRankForm.setComorder_type(form.getComorder_type());
        combRankForm.setPosition_str(form.getPosition_str());
        combRankForm.setRequest_num(form.getRequest_num());
        combRankForm.setCombine_kind(form.getCombine_kind());
        combRankForm.setUser_type(form.getUser_type());
        combRankForm.setEn_combi_status(form.getEn_combi_status());
        combRankForm.setCombi_code(form.getCombi_code());
        combRankForm.setCombi_name(form.getCombi_name());
        combRankForm.setComtag_str_qry(form.getComtag_str_qry());
        if(form.getUser() != null){
            combRankForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        }
        CombRankQryBackVo combRankQryBackVo = ledT2Service.func_comb_rank(combRankForm);
        List<CombRankResult> list = combRankQryBackVo.getData_list();
        if(!combRankQryBackVo.getError_no().equals("0")){
            return VOUtil.genErrorResult(combRankQryBackVo.getError_no(),combRankQryBackVo.getError_info(),CombRankQryBackVo.class);
        }
        if(list == null){
            return VOUtil.setSuccessResult(combRankQryBackVo);
        }
        List<Long> idList = new ArrayList<>(list.size());
        for(CombRankResult result : list){
            idList.add(Long.valueOf(result.getUser_id()));
        }
        Map<Long,UserEntityVO> avatarMap = this.leaderAvatarMap(idList);
        List<CombRankResult> backList = new ArrayList<>(list.size());
        for(CombRankResult result : list){
            UserEntityVO userEntityVO = avatarMap.get(Long.valueOf(result.getUser_id()));
            if(userEntityVO!=null){
                result.setLeader_avatar(userEntityVO.getAvatar());
                result.setAlias_name(userEntityVO.getAlias_name());
            }
            backList.add(result);
        }
        combRankQryBackVo.setData_list(backList);
        return combRankQryBackVo;
    }


    private Map<Long,UserEntityVO> leaderAvatarMap(List<Long> list){
        UsersQueryVo  usersQueryVo = userCenterService.func_users_query(StringUtils.join(list, ","));
        //查询结果集转成map
        List<UserEntityVO> userList = usersQueryVo.getData_list();
        Map<Long,UserEntityVO> map = new HashMap<>(userList.size());
        for(UserEntityVO user : userList){
            user.setAlias_name(StringUtil.replaceMobile(user.getAlias_name()));
            map.put(user.getUser_id(),user);
        }
        return map;
    }


//    @Override
//    public CombEntrustVo comb_entrust_add(MiddleCombEntrustForm form) {
//        CombEntrustForm combEntrustForm = new CombEntrustForm();
//        BeanUtils.copyProperties(form,combEntrustForm);
//        CombEntrustVo combEntrustVo = ledT2Service.func_comb_entrust_add(combEntrustForm);
//        if(VOUtil.isSuccess(combEntrustVo)){
//            PushRegIdVo pushRegIdVo = new PushRegIdVo();
//            pushRegIdVo.setRegistration_id();
//            pushRegIdVo.setMessage_title();
//            pushRegIdVo.setContent();
//            pushRegIdVo.setApp_key();
//            pushRegIdVo.setApp_secret();
//            pushExtService.sendAllNotificationWithRegId(pushRegIdVo);
//        }
//        return null;
//    }

    /**
     * 组合基本信息查询
     * @param form
     * @return
     */
    public MiddleCombineBasicInfoList combineBasicInfo(CombineMidBasicInfoform form) {
        CombDetailForm combDetailForm = new CombDetailForm();
        combDetailForm.setOp_branch_no(form.getOp_branch_no());
        combDetailForm.setOp_entrust_way(form.getOp_entrust_way());
        combDetailForm.setOp_station(form.getOp_station());
        combDetailForm.setBranch_no(form.getBranch_no());
        combDetailForm.setPassword(form.getPassword());
        combDetailForm.setPassword_type(form.getPassword_type());
        combDetailForm.setUser_token(form.getUser_token());
        combDetailForm.setSendercomp_id(form.getSendercomp_id());
        String user_id = form.getUser_id()==null?null:String.valueOf(form.getUser_id());
        combDetailForm.setUser_id(user_id);
        combDetailForm.setCombi_code(form.getCombi_code());
        CombDetailQryBackVo combDetailQryBackVo = ledT2Service.func_comb_details(combDetailForm);

        List<MiddleCombineBasicInfoData> dataList = new ArrayList<>();
        List<CombDetailResult> list = combDetailQryBackVo.getData_list();
        if (!"0".equals(combDetailQryBackVo.getError_no())){
            return VOUtil.genBGErrorResult(combDetailQryBackVo.getError_no(),
                    combDetailQryBackVo.getError_info(),
                    MiddleCombineBasicInfoList.class);
        }
        if(list == null) {
            return VOUtil.setSuccessResult(new MiddleCombineBasicInfoList());
        }

        for (CombDetailResult combDetailResult : list) {
            MiddleCombineBasicInfoData data = new MiddleCombineBasicInfoData();
            BeanUtils.copyProperties(combDetailResult,data);
            MaxRetreatQryForm maxRetreatQryForm=new MaxRetreatQryForm();//最大回撤率查询
            ComdataAdviserbineSuccessrateQryForm combAdviserSucForm=new ComdataAdviserbineSuccessrateQryForm();//投顾胜率查询

            maxRetreatQryForm.setOp_branch_no(form.getOp_branch_no());//   op_branch_no	N5	操作分支机构
            maxRetreatQryForm.setOp_entrust_way(form.getOp_entrust_way());//  op_entrust_way	C1	委托方式
            maxRetreatQryForm.setOp_station(form.getOp_station()); //op_station	C255	站点地址
            maxRetreatQryForm.setBranch_no(form.getBranch_no());// branch_no	N5	分支机构
            maxRetreatQryForm.setPassword(form.getPassword());// password	C15	密码
            maxRetreatQryForm.setPassword_type(form.getPassword_type());// password_type	C1	密码类别
            maxRetreatQryForm.setUser_token(form.getUser_token());// user_token	C512	用户口令
            String userId = form.getUser_id()==null?null:String.valueOf(form.getUser_id());
            maxRetreatQryForm.setUser_id(userId);// user_id	C18	用户编号
            maxRetreatQryForm.setSendercomp_id(form.getSendercomp_id());// sendercomp_id	C20	发送机构编码
            maxRetreatQryForm.setCombi_code(form.getCombi_code());// combi_code	C32	组合代码

            combAdviserSucForm.setOp_branch_no(form.getOp_branch_no());
            combAdviserSucForm.setOp_entrust_way(form.getOp_entrust_way());
            combAdviserSucForm.setOp_station(form.getOp_station());
            combAdviserSucForm.setBranch_no(form.getBranch_no());
            combAdviserSucForm.setPassword(form.getPassword());
            combAdviserSucForm.setPassword_type(form.getPassword_type());
            combAdviserSucForm.setUser_token(form.getUser_token());
            combAdviserSucForm.setSendercomp_id(form.getSendercomp_id());
            String user_Id = form.getUser_id()==null?null:String.valueOf(form.getUser_id());
            combAdviserSucForm.setUser_id(user_Id);
            combAdviserSucForm.setBegin_date(form.getBegin_date());
            combAdviserSucForm.setEnd_date(form.getEnd_date());
            combAdviserSucForm.setCombi_code(form.getCombi_code());
            combAdviserSucForm.setQuery_flag(form.getQuery_flag());

            MaxRetreatQryVo maxRetreatQryVo=ledSecT2Service.func_extcomdata_max_withdrawal_rate_qry(maxRetreatQryForm);//后台最大回撤率
            ComdataAdviserbineSuccessrateQryBackVo oddsVo=ledSecT2Service.func_comdata_adviserbine_successrate_qry(combAdviserSucForm);//后台胜率结果
            if(!"0".equals(maxRetreatQryVo.getError_no())){
                return VOUtil.genErrorResult(maxRetreatQryVo.getError_no(),maxRetreatQryVo.getError_info(),MiddleCombineBasicInfoList.class);
            }

            if (!"0".equals(oddsVo.getError_no())) {
                return VOUtil.genBGErrorResult(oddsVo.getError_no(), oddsVo.getError_info(), MiddleCombineBasicInfoList.class);
            }

            data.setMax_withdrawal_rate(maxRetreatQryVo.getMax_withdrawal_rate());
            data.setSuccess_num(oddsVo.getSuccess_num());
            data.setFail_num(oddsVo.getFail_num());

//            CombCostForm combCostForm = new CombCostForm();
//            combCostForm.setOp_branch_no(form.getOp_branch_no());
//            combCostForm.setOp_entrust_way(form.getOp_entrust_way());
//            combCostForm.setOp_station(form.getOp_station());
//            combCostForm.setBranch_no(form.getBranch_no());
//            combCostForm.setPassword(form.getPassword());
//            combCostForm.setPassword_type(form.getPassword_type());
//            combCostForm.setUser_token(form.getUser_token());
//            combCostForm.setSendercomp_id(form.getSendercomp_id());
//            combCostForm.setCombi_code(combDetailResult.getCombi_code());
//            combCostForm.setPromotion_flag(null);
//            CombCostVo combCostVo = ledT2Service.func_comb_cost_query(combCostForm);
//            combCostForm.setPromotion_flag("0");
//            CombCostVo combCostVo1 = ledT2Service.func_comb_cost_query(combCostForm);
//            data.setComb_fare(combCostVo.getComb_fare());
//            data.setComb_fare_org(combCostVo1.getComb_fare());
            dataList.add(data);
        }
        MiddleCombineBasicInfoList middleCombineBasicInfoList = new MiddleCombineBasicInfoList();
        middleCombineBasicInfoList.setData_list(dataList);
        return VOUtil.setSuccessResult(middleCombineBasicInfoList);
    }

    @Override
    public ExtcomacctVagueQryList func_extcomacct_vague_qry(ExtcomacctVagueForm form) {//投顾模糊搜索
        ExtcomacctVagueQryForm extcomacctVagueQryForm = new ExtcomacctVagueQryForm();
        extcomacctVagueQryForm.setQuery_name(form.getQuery_name());
        extcomacctVagueQryForm.setPosition_str(form.getPosition_str());
        extcomacctVagueQryForm.setRequest_num(form.getRequest_num());
        extcomacctVagueQryForm.setOp_branch_no(form.getOp_branch_no());
        extcomacctVagueQryForm.setOp_entrust_way(form.getOp_entrust_way());
        extcomacctVagueQryForm.setOp_station(form.getOp_station());
        extcomacctVagueQryForm.setBranch_no(form.getBranch_no());
        extcomacctVagueQryForm.setPassword(form.getPassword());
        extcomacctVagueQryForm.setPassword_type(form.getPassword_type());
        extcomacctVagueQryForm.setUser_token(form.getUser_token());
        extcomacctVagueQryForm.setSendercomp_id(form.getSendercomp_id());
        if(form.getUser() !=null){
            extcomacctVagueQryForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        }

        ExtcomacctVagueQryBackVo extcomacctVagueQryBackVo = ledSecT2Service.func_extcomacct_vague_qry(extcomacctVagueQryForm);
        if (!"0".equals(extcomacctVagueQryBackVo.getError_no())){
            return VOUtil.genBGErrorResult(extcomacctVagueQryBackVo.getError_no(),
                    extcomacctVagueQryBackVo.getError_info(),ExtcomacctVagueQryList.class);
        }
        if (extcomacctVagueQryBackVo.getData_list() == null) {
            return VOUtil.setSuccessResult(new ExtcomacctVagueQryList());
        }
        List<ExtcomacctVagueQryResult> list = extcomacctVagueQryBackVo.getData_list();
        //头像封装
        List<Long> userIdlist = new ArrayList<>();
        for (ExtcomacctVagueQryResult extcomacctVagueQryResult : list) {
             userIdlist.add(Long.valueOf(extcomacctVagueQryResult.getUser_id()));
        }
        Map<Long,UserEntityVO> map =  leaderAvatarMap(userIdlist);

        ExtcomacctVagueQryList extcomacctVagueQryList = new ExtcomacctVagueQryList();
        List<ExtcomacctVagueQryBack> dataList = new ArrayList<>();
        for (ExtcomacctVagueQryResult extcomacctVagueQryResult : list) {
            ExtcomacctVagueQryBack extcomacctVagueQryBack = new ExtcomacctVagueQryBack();
            BeanUtils.copyProperties(extcomacctVagueQryResult, extcomacctVagueQryBack);
            UserEntityVO userEntityVO =  map.get(Long.valueOf(extcomacctVagueQryResult.getUser_id()));
            if(userEntityVO!=null) {
                extcomacctVagueQryBack.setLeader_avatar(userEntityVO.getAvatar());
                extcomacctVagueQryBack.setAlias_name(userEntityVO.getAlias_name());
            }
            dataList.add(extcomacctVagueQryBack);
        }
        extcomacctVagueQryList.setData_list(dataList);
        return VOUtil.setSuccessResult(extcomacctVagueQryList);
    }

    /**
     * 组合委托
     */
    public CombEntrustVo func_comb_entrust_add( CombEntrustTransForm param){
         CombEntrustForm combEntrustForm = JSON.parseObject(JSON.toJSONString(param),CombEntrustForm.class);
        combEntrustForm.setUser_token(param.getUser_token());
        combEntrustForm.setUser_id(param.getUser().getUser_id()+"");
        return lightinvestingService.func_comb_entrust_add(combEntrustForm);
    }

    /**
     * 组合关注，即领投宝的组合订阅
     */
    public CombSubscribeVo func_combine_focus(CombSubscribeTransForm param){
        CombSubscribeForm   combSubscribeForm = JSON.parseObject(JSON.toJSONString(param),CombSubscribeForm.class);
        combSubscribeForm.setUser_token(param.getUser_token());
        combSubscribeForm.setUser_id(param.getUser().getUser_id()+"");
        combSubscribeForm.setPartner_id(ConfigUtil.getString(param.getCompany_id(),"wx.app.partnerId","0"));
        CombSubscribeVo combSubscribeVo = lightinvestingService.func_combine_focus(combSubscribeForm);
        //TODO 判断是否支付
        if (VOUtil.isSuccess(combSubscribeVo)
                && param.getPrepay_balance() == 0d && param.getCompany_id().equals("20020")) {
            TagsAddForm tagsAddForm = new TagsAddForm();
            tagsAddForm.setCompany_id("20020");
            tagsAddForm.setSendercomp_id("20020");
            tagsAddForm.setUser_id(param.getUser().getUser_id());
            tagsAddForm.setTag(param.getCombi_code());
            pushService.xinanTagsAdd(tagsAddForm);
        }
//        if (VOUtil.isSuccess(combSubscribeVo) && param.getCompany_id().equals("20020")) {
//            CombCostForm form = new CombCostForm();
//            form.setCombi_code(param.getCombi_code());
//            form.setUser_token(param.getUser_token());
//            CombCostVo combCostVo = ledT2Service.func_comb_cost_query(form);
//            if (VOUtil.isSuccess(combCostVo) && combCostVo.getFare_per_month() == 0d) {
//                TagsAddForm tagsAddForm = new TagsAddForm();
//                tagsAddForm.setCompany_id("20020");
//                tagsAddForm.setSendercomp_id("20020");
//                tagsAddForm.setUser_id(param.getUser().getUser_id());
//                tagsAddForm.setTag(param.getCombi_code());
//                pushService.xinanTagsAdd(tagsAddForm);
//            } else {
//                //根据组合代码查询投顾id
//                CombDetailForm combDetailForm = new CombDetailForm();
//                combDetailForm.setOp_branch_no(param.getOp_branch_no());
//                combDetailForm.setOp_entrust_way(param.getOp_entrust_way());
//                combDetailForm.setOp_station(param.getOp_station());
//                combDetailForm.setBranch_no(param.getBranch_no());
//                combDetailForm.setPassword(param.getPassword());
//                combDetailForm.setPassword_type(param.getPassword_type());
//                combDetailForm.setUser_token(param.getUser_token());
//                combDetailForm.setSendercomp_id(param.getSendercomp_id());
//                combDetailForm.setCombi_code(param.getCombi_code());
//                CombDetailQryBackVo combDetailQryBackVo = ledT2Service.func_comb_details(combDetailForm);
//                if (VOUtil.isSuccess(combDetailQryBackVo)
//                        && combDetailQryBackVo.getData_list() != null && combDetailQryBackVo.getData_list().size() > 0) {
//                    CombDetailResult combDetailResult = combDetailQryBackVo.getData_list().get(0);
//                    //查询用户已签约达人
//                    ComuserSignQryForm ledT2Form = new ComuserSignQryForm();
//                    ledT2Form.setSendercomp_id(param.getUser().getSendercomp_id());
//                    ledT2Form.setUser_id(String.valueOf(param.getUser().getUser_id()));
//                    ledT2Form.setUser_token(param.getUser_token());
//                    ledT2Form.setNeed_user_id(param.getNeed_user_id());
//                    ComuserSignQryBackVo comuserSignQryBackVo = lightinvestingService.func_comuser_sign_qry(ledT2Form);
//                    if (VOUtil.isSuccess(comuserSignQryBackVo)
//                            && comuserSignQryBackVo.getData_list() != null && comuserSignQryBackVo.getData_list().size() > 0) {
//                        for (ComuserSignQry comuserSignQry : comuserSignQryBackVo.getData_list()) {
//                            //判断是否签约过投顾
//                            if (comuserSignQry.getAdviser_id().equals(combDetailResult.getUser_id())) {
//                                TagsAddForm tagsAddForm = new TagsAddForm();
//                                tagsAddForm.setCompany_id("20020");
//                                tagsAddForm.setSendercomp_id("20020");
//                                tagsAddForm.setUser_id(param.getUser().getUser_id());
//                                tagsAddForm.setTag(param.getCombi_code());
//                                pushService.xinanTagsAdd(tagsAddForm);
//                                break;
//                            }
//                        }
//                    }
//                }
//            }
//        }
        return combSubscribeVo;
    }

    /**
     * 投顾收藏，即领投宝的投顾关注
     */
    public InterestFocusVo func_focus_interest_add( FocusInterestByTransForm param){
        FocusInterestByForm   focusInterestByForm = JSON.parseObject(JSON.toJSONString(param),FocusInterestByForm.class);
        focusInterestByForm.setUser_token(param.getUser_token());
        focusInterestByForm.setUser_id(param.getUser().getUser_id()+"");
        return lightinvestingService.func_focus_interest_add(focusInterestByForm);
    }


    @Override
    public SubscriptionCombineQryBackVo func_comb_subscription(MiddleSubscriptionCombineForm form) {
        SubscriptionCombineForm subscriptionCombineForm = new SubscriptionCombineForm();
        BeanUtils.copyProperties(form,subscriptionCombineForm);
        SubscriptionCombineQryBackVo back = ledT2Service.func_comb_subscription(subscriptionCombineForm);
        if(!VOUtil.isSuccess(back)){
            return VOUtil.genBGErrorResult(back.getError_no(),back.getError_info(),SubscriptionCombineQryBackVo.class);
        }
        List<SubscriptionCombineResult> list = back.getData_list();
        if(list==null || list.size()==0){
            return VOUtil.setSuccessResult(new SubscriptionCombineQryBackVo());
        }
        List<Long> idList = new ArrayList<>(list.size());
        for(SubscriptionCombineResult result : list){
            idList.add(Long.valueOf(result.getUser_id()));
        }
        Map<Long,UserEntityVO> map = this.leaderAvatarMap(idList);
        List<SubscriptionCombineResult> backList = new ArrayList<>();
        for(SubscriptionCombineResult result : list){
            UserEntityVO userEntityVO = map.get(Long.valueOf(result.getUser_id()));
            if(userEntityVO!=null){
                result.setLeader_avatar(userEntityVO.getAvatar());
                result.setAlias_name(userEntityVO.getAlias_name());
            }
            backList.add(result);
        }
        back.setData_list(backList);
        return back;
    }

    @Override
    public CombSubscribeCancelVo func_combine_focus_cancel(MiddleCombSubscribeCancelForm form) {
        CombSubscribeCancelForm combSubscribeCancelForm = new CombSubscribeCancelForm();
        BeanUtils.copyProperties(form,combSubscribeCancelForm);
        combSubscribeCancelForm.setUser_id(String.valueOf(form.getUser().getUser_id()));
        combSubscribeCancelForm.setCombi_code(form.getCombi_code());
        combSubscribeCancelForm.setRemark(form.getRemark());
        CombSubscribeCancelVo combSubscribeCancelVo = ledT2Service.func_combine_focus_cancel(combSubscribeCancelForm);
        if(VOUtil.isSuccess(combSubscribeCancelVo)){
            TagsRemoveForm tagsRemoveForm = new TagsRemoveForm();
            tagsRemoveForm.setCompany_id("20020");
            tagsRemoveForm.setSendercomp_id("20020");
            tagsRemoveForm.setUser_id(form.getUser().getUser_id());
            tagsRemoveForm.setTag(form.getCombi_code());
            pushService.xinanTagsDelete(tagsRemoveForm);
        }
        return combSubscribeCancelVo;
    }
}
